/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ill_be_bach.view;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Hashtable;
import javax.swing.JPanel;

/**
 *
 * @author Abhi
 */
public class KeyboardRenderer {

    private static final int BLACK_WIDTH_RATIO = 2 ;
    private static final int BLACK_HEIGHT_RATIO = 2 ;

    private Hashtable<Integer, Boolean> keysPressed = new Hashtable<Integer, Boolean>() ;

    public static int calcBlackNoteHeight(JPanel panel, int numKeys) {
        return calcKeyHeight(panel, numKeys) / BLACK_HEIGHT_RATIO;
    }

    public static int calcBlackNoteWidth(JPanel panel, int numKeys) {
        return calcKeyWidth(panel, numKeys) / BLACK_WIDTH_RATIO;
    }

    public static int calcKeyHeight (JPanel panel, int numKeys) {
        return panel.getHeight() - 1 ;
    }

    public static int calcKeyWidth (JPanel panel, int numKeys) {
        return panel.getWidth() / numKeys ;
    }

    public void draw(Graphics g, JPanel panel, int numKeys, int keyPressedIndex, boolean sharpPressed, boolean chordMode) {
        Graphics2D g2d = (Graphics2D)g;

        int keyWidth = calcKeyWidth(panel, numKeys) ;
        int keyHeight = calcKeyHeight(panel, numKeys) ;

        if (!chordMode)
            keysPressed.clear();
        keysPressed.put(keyPressedIndex, sharpPressed);

        for (int keyIndex = 0 ; keyIndex < numKeys ; keyIndex++) {
            boolean keyPressed = keysPressed.keySet().contains(keyIndex) && !keysPressed.get(keyIndex);
            g2d.setColor(Color.BLACK);
            g2d.draw3DRect(keyIndex * keyWidth, 0, keyWidth, keyHeight, !keyPressed);
            g2d.setColor(Color.WHITE);
            g2d.fill3DRect(keyIndex * keyWidth, 0, keyWidth, keyHeight, !keyPressed);
        }
        for (int keyIndex = 0 ; keyIndex < numKeys ; keyIndex++) {
            int baseKeyIndex = keyIndex % 7 ;
            if ((baseKeyIndex == 0 || baseKeyIndex == 1 || baseKeyIndex == 3
                    || baseKeyIndex == 4 || baseKeyIndex == 5) && keyIndex != numKeys - 1) {
                boolean keyPressed = keysPressed.keySet().contains(keyIndex) && keysPressed.get(keyIndex);
                g2d.setColor(!keyPressed? Color.BLACK : Color.GRAY);
                g2d.fill3DRect(keyIndex * keyWidth + keyWidth - keyWidth/(BLACK_WIDTH_RATIO*2), 0, keyWidth/BLACK_WIDTH_RATIO, keyHeight/BLACK_HEIGHT_RATIO, !keyPressed);
            }
        }
    }
}
